using System.Collections.Generic;

namespace Gj
{
    public class StatisticsService : GameService
    {
        public static StatisticsService single;

        private Dictionary<string, ObjectData> store;

        static StatisticsService()
        {
            single = new StatisticsService();
        }

        public void OnDestroy()
        {
            single = new StatisticsService();
        }

        public void OnInit()
        {
            store = new Dictionary<string, ObjectData>();
        }

        public void OnUpdate()
        {
            
        }

        public void Register(string id, ObjectData data)
        {
            if (LoadData(id) == null) SaveData(id, data);
        }

        private ObjectData LoadData(string id)
        {
            if (store.ContainsKey(id)) return store[id];
            return null;
        }

        private void SaveData(string id, ObjectData data)
        {
            store.Add(id, data);
        }

        public float Count(string id, int type)
        {
            return Get(id, type) + SubCount(id, type);
        }

        private float SubCount(string masterId, int type)
        {
            var list = RelationService.single.LoadSub(masterId);
            if (list == null) return 0;
            float count = 0;
            foreach (var id in list) count += Get(id, type);
            return count;
        }

        private float Get(string id, int type)
        {
            var data = LoadData(id);
            if (data == null) return 0;
            return data[type];
        }
    }
}